import axios from 'axios'
import md5 from 'md5'
import { storage } from 'webextension-polyfill'
import {token, user} from '~/logic'


// axios.defaults.baseURL = import.meta.env.PROD ? 'https://api.xingcha365.com' : 'http://192.168.31.42:8889'
axios.defaults.baseURL = 'https://api.xingcha365.com'
axios.interceptors.request.use(async (config) => {
  if (config.url?.indexOf('http') === 0 || config.url?.indexOf('//') === 0)
    return config

  const authorization = token.value
  if (authorization !== '')
    config.headers.Authorization = authorization

  if (!config.params)
    config.params = {}

  config.params.t = Math.floor(new Date().getTime() / 1000)
  const params = config.params
  if (params) {
    const keys = Object.keys(params).sort()
    let str = ''
    keys.forEach((key) => {
      str += params[key]
    })
    config.headers['Request-Sign'] = md5(`${str}b03f202406f2c42a4b1ee8eb0c7497b9`)
  }
  if (config.method === 'post') {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    config.data = Object.keys(config.data).map((key) => {
      return `${key}=${config.data[key]}`
    }).join('&')
  }

  return config
})
axios.interceptors.response.use((response) => {
  return response
}, (error) => {
  if (error.code === 401){
    token.value = ''
    user.value = undefined
  }
  return Promise.resolve(error.response)
})
export default axios
